package com.yj.core.exception.handler;

import com.yj.core.exception.ApiException;
import com.yj.core.exception.ServiceException;
import com.yj.core.result.BaseExceptionMsg;
import com.yj.core.result.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 异常处理器
 *
 * @author cyj
 * @date 19-03-13
 */
@Slf4j
@Order(Integer.MIN_VALUE)
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    private static final String EXCEPTION_LOG = "服务具体异常:";

    /**
     * 远程调用异常处理
     */
    @ExceptionHandler(ApiException.class)
    public JsonResult apiException(ApiException e) {
        log.error(EXCEPTION_LOG, e);
        return new JsonResult(e.getCode(), e.getMessage());
    }

    /**
     * 业务逻辑异常的处理
     */
    @ExceptionHandler(ServiceException.class)
    public JsonResult serviceException(ServiceException e) {
        log.error(EXCEPTION_LOG, e);
        return new JsonResult(e.getCode(), e.getMessage());
    }


    /**
     * 参数异常处理
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public JsonResult apiException(IllegalArgumentException e) {
        log.error(EXCEPTION_LOG, e);
        return new JsonResult(BaseExceptionMsg.EXECUTE_FAILD);
    }

    /**
     * 运行时异常处理
     */
    @ExceptionHandler(RuntimeException.class)
    public JsonResult apiException(RuntimeException e) {
        log.error(EXCEPTION_LOG, e);
        return new JsonResult(BaseExceptionMsg.EXECUTE_FAILD);
    }

    /**
     * 参数校验异常处理
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult apiException(MethodArgumentNotValidException e) {
        log.error(EXCEPTION_LOG, e);
        return new JsonResult(BaseExceptionMsg.PARAM_INVALID, e.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * 新增数据违反唯一约束
     */
    @ExceptionHandler(DuplicateKeyException.class)
    public JsonResult apiException(DuplicateKeyException e) {
        log.error(EXCEPTION_LOG, e);
        return new JsonResult(BaseExceptionMsg.DATA_EXIST);
    }
}
